#include "../inc/infrared.h"

uint8_t buf[32]; 
uint8_t len = 2;

/**
 * @brief Calculate the checksum of the data.
 * @param data Pointer to the data.
 * @param len Length of the data.
 * @return Checksum of the data.
 */
uint8_t getSum(uint8_t *data, uint8_t len)
{
    uint8_t i, sum = 0;
    for (i = 0; i < len; i++)
    {
        sum += data[i];
    }
    return sum;
}

/**
 * @brief Prepare infrared study command.
 * @param data Pointer to the data buffer.
 * @param group Group number.
 * @return Length of the prepared command.
 */
uint8_t IrStudy(uint8_t *data, uint8_t group)
{
    uint8_t *offset = data, cs;
    *offset++ = 0x68;
    *offset++ = 0x08;
    *offset++ = 0x00;
    *offset++ = 0xff;
    *offset++ = 0x10;
    *offset++ = group;
    cs = getSum(&data[3], offset - data - 3);
    *offset++ = cs;
    *offset++ = 0x16;
    return offset - data;
}

/**
 * @brief Prepare infrared send command.
 * @param data Pointer to the data buffer.
 * @param group Group number.
 * @return Length of the prepared command.
 */
uint8_t IrSend(uint8_t *data, uint8_t group)
{
    uint8_t *offset = data, cs;
    *offset++ = 0x68;
    *offset++ = 0x08;
    *offset++ = 0x00;
    *offset++ = 0xff;
    *offset++ = 0x12;
    *offset++ = group;
    cs = getSum(&data[3], offset - data - 3);
    *offset++ = cs;
    *offset++ = 0x16;
    return offset - data;
}

/**
 * @brief Initialize the infrared module.
 */
void infrared_init(void)
{
    uapi_uart_deinit(UART2);
    IotUartAttribute g_uart_cfg = {UART_BAUDRATE, UART_DATA_BITS, UART_STOP_BITS, IOT_UART_PARITY_NONE, 100, 100, 0};
    IoTUartInit(UART2, &g_uart_cfg);
}

/**
 * @brief Configure UART2.
 */
void uart2_config(void)
{
    uapi_uart_deinit(UART2);
    IotUartAttribute g_uart_cfg = {115200, 8, 1, IOT_UART_PARITY_NONE, 100, 100, 0};
    IoTUartInit(UART2, &g_uart_cfg);
}

/**
 * @brief Send AC power on command.
 */
void send_ac_power_on(void)
{
    len = IrSend(buf, 0);
}

/**
 * @brief Send AC power off command.
 */
void send_ac_power_off(void)
{
    len = IrSend(buf, 1);
    IoTUartWrite(CONFIG_UART_BUS_ID, buf, len);
}
